import { ReactNode, useEffect, useMemo } from 'react'
import { UIMatch, useMatches } from 'react-router'

import { IRouteHandle } from './interface'

const SEPARATOR = ' · '

export const SetTitle = Object.assign(
  function SetTitle({ children }: { children: ReactNode }) {
    const matches = useMatches() as UIMatch<unknown, IRouteHandle | undefined>[]

    const name = useMemo(
      () =>
        matches
          .map(d => d.handle?.name?.(d as UIMatch<unknown, IRouteHandle>))
          .filter(d => typeof d === 'string' && d && d.trim() !== $APP)
          .reverse()
          .concat($APP)
          .slice(0, 2)
          .join(SEPARATOR),
      [matches],
    )

    useEffect(() => {
      if (name) {
        document.title = name
      }
    }, [name])

    return <>{children}</>
  },

  {
    /** 标题分隔符 */
    SEPARATOR: SEPARATOR as typeof SEPARATOR,
  },
)
